<template>
  <div class="login-enter">
    <div class="login-title">{{ $t('login.login') }}</div>
    <div class="enter-form">
      <el-form ref="enterRef" :model="enterForm" :rules="enterRules">
        <el-form-item prop="name">
          <el-input
            v-model="enterForm.name"
            :placeholder="$t('login.enter-username')"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="enterForm.password"
            type="password"
            show-password
            :placeholder="$t('login.enter-password')"
          />
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="display-flex slider">
            <core-slider-captcha
              @success="captchaSuccess"
              :style="[
                noCaptcha &&
                  'border-color: rgb(var(--core-error-color)); transition: border-color 0.2s var(--el-transition-function-ease-in-out-bezier)'
              ]"
              :text="$t('login.drag-to-slide')"
              :success-text="$t('login.verification-passed')"
            ></core-slider-captcha>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="account-actions display-flex flex-align flex-justify-between">
      <el-checkbox v-model="rememberAccount">{{
        $t('login.remember-account')
      }}</el-checkbox>
      <span
        class="forgot-password"
        @click="handleNavigate('/login/forget-password')"
        >{{ $t('login.forget-password') }}?</span
      >
    </div>
    <el-button
      class="login-button"
      type="primary"
      :loading="loginLoading"
      @click="handleLogin"
      >{{ $t('login.login') }}</el-button
    >
    <other-login @navigate="handleNavigate"></other-login>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, unref, useTemplateRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import OtherLogin from './components/other/index.vue'
import { loginPasswordRegex } from '@/utils/modules/regexp'
import { delay } from '@/utils'
import { usePreferencesStore } from '@/stores'
import { useI18n } from 'vue-i18n'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const preferencesStore = usePreferencesStore()

const LOGIN_REMEMBER_ACCOUNT = 'LOGIN_REMEMBER_ACCOUNT'
const localUsername = localStorage.getItem(LOGIN_REMEMBER_ACCOUNT) || ''

const enterForm = ref({
  name: localUsername,
  password: '',
  captcha: false
})
const noCaptcha = ref(false)
const checkCaptcha = (_rule: RuleItem, value: boolean, cd: RuleItemCb) => {
  if (!value) {
    noCaptcha.value = true
    return cd(new Error(t('login.complete-verification')))
  }
  noCaptcha.value = false
  cd()
}
const enterRules = reactive<FormRules<typeof enterForm.value>>({
  name: [
    { required: true, message: t('login.enter-username'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('login.enter-password'), trigger: 'blur' },
    {
      pattern: loginPasswordRegex,
      message: t('login.password-format-error'),
      trigger: ['change', 'blur']
    }
  ],
  captcha: [{ validator: checkCaptcha }]
})
const enterRef = useTemplateRef<FormInstance>('enterRef')

const captchaSuccess = (val: { isPassing: boolean }) => {
  enterForm.value.captcha = val.isPassing
  if (val.isPassing) {
    const enterEl = unref(enterRef)
    enterEl?.validateField('captcha')
  }
}

const loginLoading = ref(false)
const handleLogin = async () => {
  loginLoading.value = true
  try {
    await enterRef.value?.validate()
    await delay(500)
    handleRememberAccount()
    handleAfterLogin()
  } catch (error) {
    return error
  } finally {
    loginLoading.value = false
  }
}

const handleRememberAccount = () => {
  if (rememberAccount.value) {
    localStorage.setItem(LOGIN_REMEMBER_ACCOUNT, enterForm.value.name)
  } else {
    localStorage.removeItem(LOGIN_REMEMBER_ACCOUNT)
  }
}

const handleAfterLogin = () => {
  if (route.query.redirect) {
    router.replace(route.query.redirect as string)
  } else {
    router.replace('/')
  }
}

const rememberAccount = ref(!!localUsername)

const handleNavigate = (path: string) => {
  router.replace(path)
}

watch(
  () => preferencesStore.general.lang.language,
  () => {
    if (enterRules.name && Array.isArray(enterRules.name)) {
      enterRules.name[0].message = t('login.enter-username')
    }
    if (enterRules.password && Array.isArray(enterRules.password)) {
      enterRules.password[0].message = t('login.enter-password')
      enterRules.password[1].message = t('login.password-format-error')
    }
  }
)

defineOptions({
  name: 'CoreEnter'
})
</script>

<style scoped lang="scss">
.login-enter {
  margin: 24px 54px;

  .login-title {
    margin-bottom: 22px;
    font-size: 36px;
    font-weight: 700;
  }

  .slider {
    width: 100%;
    height: var(--core-component-size);
  }

  .account-actions {
    font-size: 14px;

    .forgot-password {
      color: rgb(var(--core-primary-color));
      cursor: pointer;
    }
  }

  .login-button {
    width: 100%;
    margin: 16px 0;
  }
}
</style>
